import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    arr: localStorage.getItem("arr") ? JSON.parse(localStorage.getItem("arr")) :
    [{
        pname: "联想笔记本电脑",
        id: 88,
        uptDate: new Date(),
        price: 6000,
        count: 50,
        user: "张三",
        isShow: true
      },
      {
        pname: "宏基笔记本电脑",
        id: 99,
        uptDate: new Date(),
        price: 8000,
        count: 30,
        user: "里斯",
        isShow: true
      },
    ],
  },
  getters: {
    getTotal(state) {
      return state.arr.reduce((pre, curr) => pre + curr.price * curr.count, 0);
    }
  },
  mutations: {
    //查询方法，修改isShow属性
    search(state, payload) {
      console.log("search...");

      state.arr.forEach(item => {
        item.isShow = item.pname.includes(payload)
      })
    },
    //删除单个
    delPro(state, idx) {
      state.arr.splice(idx, 1);
    },
    //批量删除
    delProAll(state, payload) {
      //遍历要删除的id，逐个删除
      payload.forEach(id => {
        let curindex = state.arr.findIndex(item => item.id == id)
        console.log("要删除的索引：", curindex); 
        if (curindex != -1) {
          state.arr.splice(curindex, 1);
        }
      })
    },
    //添加
    addPro(state, payload) {
      state.arr.push(payload);
    },
    //编辑
    editPro(state, payload) {
      let idx = state.arr.findIndex(item => item.id == payload.id);
      state.arr[idx].pname = payload.pname;
      state.arr[idx].uptDate = payload.uptDate;
      state.arr[idx].price = payload.price;
      state.arr[idx].count = payload.count;
      state.arr[idx].user = payload.user;
    }

  },
  actions: {},
  modules: {}
})